using IQIGame.Onigao.Game;
using IQIGame.Onigao.GamePlay;
using System.Collections.Generic;

namespace IQIGame.Onigao.Logic
{
    /// <summary>
    /// 修改实体服务
    /// 参数：1：实体tag（填0表示自己），2+：服务列表
    /// </summary>
    public class ExecChangeService : BaseServiceExecution
    {
        public override void Execute(LevelRegion region, LevelPlayer player)
        {
            var config = _config as ExecParamChangeService;
            if (!config.tagOrMcid.TryGetValue(triggerEntity, out int tagOrMcid))
            {
                LogicLog.LogError("无法获取到tagOrMcid.");
                return;
            }

            if (tagOrMcid == 0)
            {
                if (triggerEntity != null)
                {
                    region.level.delayServiceMgr.CancelDelayByEntity(triggerEntity.id);
                    triggerEntity.serviceMgr.Refresh(config.services); //修改服务后会导致原先的服务被释放，可能包括本执行，可能导致triggerEntity被置空
                }
                else
                {
                    LogicLog.LogError($"根据TagOrMcid[{tagOrMcid}]找不到任何实体。");
                }
            }
            else
            {
                List<LevelEntity> modifyEntitys = ListPool<LevelEntity>.Get();
                {
                    region.GetEntitiesByTagOrMcid(tagOrMcid, modifyEntitys, true);
                    if (modifyEntitys.Count > 0)
                    {
                        foreach (LevelEntity entity in modifyEntitys)
                        {
                            triggerEntity.serviceMgr.Refresh(config.services);
                            region.level.delayServiceMgr.CancelDelayByEntity(entity.id);
                        }
                    }
                    else
                    {
                        LogicLog.LogError($"根据TagOrMcid[{tagOrMcid}]找不到任何实体。");
                    }

                    ListPool<LevelEntity>.Put(modifyEntitys);
                }
            }
        }
    }
}
